package com.hilin.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hilin.base.service.AccountService;
import com.hilin.common.common.handler.RequestTokenHandler;
import com.hilin.common.util.EncryptUtils;
import com.hilin.common.util.RandomUtils;
import com.hilin.entity.vo.SignVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.freeswitch.esl.client.IEslEventListener;
import org.freeswitch.esl.client.test.FsClient;
import org.freeswitch.esl.client.test.FsClientUtils;
import org.freeswitch.esl.client.test.FsEventType;
import org.freeswitch.esl.client.transport.event.EslEvent;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

@EnableCaching
@EnableSwagger2
@MapperScans({
        @MapperScan("com.hilin.base.dao.mapper")
})
@Slf4j
@SpringBootApplication(
        exclude = {}
)
public class BaseApplication extends WebMvcConfigurationSupport implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(BaseApplication.class, args);
    }

    @Autowired
    private RequestTokenHandler handler;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        registry.addInterceptor(handler);
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // .groupName("所有接口")
                // apiInfo指定测试文档基本信息，这部分将在页面展示
                .apiInfo(apiInfo()).select()
                // apis() 控制哪些接口暴露给swagger，
                // RequestHandlerSelectors.any() 所有都暴露
                // 指定包位置
                .apis(RequestHandlerSelectors.basePackage("com.hilin.base.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    // 基本信息，页面展示
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("基础服务")
                // 版本号
                .version("1.0.0-SNAPSHOT").build();
    }

    @Autowired
    private AccountService accountService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        SignVo signVo = new SignVo();
        signVo.setOrgId(1L);
        signVo.setNonce(RandomUtils.genRandomStr(24));
        signVo.setTimestamp(System.currentTimeMillis() / 1000);
        String signStr = signVo.getNonce() + signVo.getOrgId() + signVo.getTimestamp() + "m7EwTQPe1BTXEYPOTYPNYqMR";
        log.warn("输入的原始字符串:{}", signStr);
        signVo.setSign(EncryptUtils.getMd5(signStr));

        System.out.println(accountService.serviceGenToken(signVo));
        new Thread(new Runnable() {
            @Override
            @SneakyThrows
            public void run() {
                FsClient currentClient = new FsClient();
                currentClient.connect("192.168.0.86", 8021, "ClueCon", 10);
                FsClientUtils.setEventFilter(currentClient, FsEventType.values());
                log.info("开始注册事件监听器");
                currentClient.addEventListener(new IEslEventListener() {
                    // 接收监听事件
                    @Override
                    public void eventReceived(EslEvent event) {
                        log.info("事件开始==================\n{}\n{}", event.getEventName(),
                                JSON.toJSONString(event.getEventHeaders(),
                                        (PropertyFilter) (object, name, value) -> !name.toUpperCase().contains("variable".toUpperCase()),
                                        SerializerFeature.PrettyFormat));
                        mongoTemplate.insert(event, "fs-event");
                    }

                    // TODO 暂时不知道作用
                    @Override
                    public void backgroundJobResultReceived(EslEvent eslEvent) {
                    }
                });
            }
        });
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(0, new MappingJackson2HttpMessageConverter());
    }
}
